<template>
  <canvas ref="canvas" class="background-canvas"></canvas>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

// Canvas 引用
const canvas = ref(null)
let ctx = null

// 节点配置
const nodes = []
const nodeCount = 500
const maxDistance = 200 // 节点连线最大距离
const speed = 0.5 // 节点移动速度

// 初始化节点
function createNodes() {
  for (let i = 0; i < nodeCount; i++) {
    nodes.push({
      x: Math.random() * canvas.value.width,
      y: Math.random() * canvas.value.height,
      vx: (Math.random() - 0.5) * speed,
      vy: (Math.random() - 0.5) * speed,
      radius: Math.random() * 2 + 1
    })
  }
}

// 绘制单个节点
function drawNode(node) {
  ctx.beginPath()
  ctx.arc(node.x, node.y, node.radius, 0, Math.PI * 2)
  ctx.fillStyle = 'rgba(70, 184, 255, 0.6)'
  ctx.fill()
}

// 绘制连接线
function drawLines() {
  for (let i = 0; i < nodes.length; i++) {
    for (let j = i + 1; j < nodes.length; j++) {
      const dx = nodes[i].x - nodes[j].x
      const dy = nodes[i].y - nodes[j].y
      const distance = Math.sqrt(dx * dx + dy * dy)

      if (distance < maxDistance) {
        const opacity = 1 - distance / maxDistance
        ctx.strokeStyle = `rgba(70, 184, 255, ${opacity})`
        ctx.lineWidth = 0.8
        ctx.beginPath()
        ctx.moveTo(nodes[i].x, nodes[i].y)
        ctx.lineTo(nodes[j].x, nodes[j].y)
        ctx.stroke()
      }
    }
  }
}

// 更新节点位置
function updateNodes() {
  for (const node of nodes) {
    node.x += node.vx
    node.y += node.vy

    // 边界反弹
    if (node.x < 0 || node.x > canvas.value.width) node.vx *= -1
    if (node.y < 0 || node.y > canvas.value.height) node.vy *= -1
  }
}

// 动画循环
function animate() {
  if (!ctx) return

  // 清除画布
  ctx.clearRect(0, 0, canvas.value.width, canvas.value.height)

  // 更新 & 绘制
  updateNodes()
  drawLines()
  nodes.forEach(drawNode)

  requestAnimationFrame(animate)
}

// 窗口大小变化时重置
function resizeCanvas() {
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight
}

// 初始化
function init() {
  ctx = canvas.value.getContext('2d')
  nodes.length = 0
  createNodes()
  animate()
}

// 生命周期
onMounted(() => {
  resizeCanvas()
  init()
  window.addEventListener('resize', resizeCanvas)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCanvas)
})
</script>

<style lang="scss" scoped>
.background-canvas {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: #e0f7ff;
}
</style>